'use strict'
const moment = require('moment')
const stringRandom = require('string-random')

module.exports = () => {
  return async function (ctx, next) {
    const { app } = ctx
    const { redis } = app
    const level = 'REQ'

    await next()

    // 记录每一个请求
    const ERR_PREFIX = `client_server_err:${level}`
    const ERR_ID = `${(+new Date()).toString()}-${stringRandom(8)}`
    const ERR_KEY = `${ERR_PREFIX}:${ERR_ID}`

    const errInfo = {
      path: ctx.request.originalUrl,
      reqIp: ctx.ip,
      //   ctx.req.headers['x-forwarded-for'] ||
      //   ctx.req.connection.remoteAddress ||
      //   ctx.req.socket.remoteAddress ||
      //   ctx.req.connection.socket.remoteAddress,
      time: moment().format('YYYY-MM-DD HH:mm:ss'),
      request: ctx.request.body,
      response: ctx.response.body,
    }

    // 先插入详细报错数据
    await redis.set(ERR_KEY, JSON.stringify(errInfo))
    // 设置过期时间（单位：秒）
    redis.expire(ERR_KEY, 3600)
  }
}
